#-*-coding:utf-8-*-
__author__ = 'toriycn'
'''
   业务处理模块，由这里处理一些数据
'''

import  threading
from app.monitors.server.conf import  hosts,settings
from app.monitors.server.core import  main
import time
from app.utils import LogUtil,SSHUtil,DictUtil
import traceback

'''
  这里启动一个监控的服务器端，然后，后台根据需要进行调用；
'''
class BusinessMonitorServer(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.server = main.MonitorServer()

    def run(self):
       self.server.config_hosttemplate()
       self.server.start()

    def getServer(self):
        return self.server


#启动监控主程序
bmonitorServer = BusinessMonitorServer()
bmonitorServer.setDaemon(True)
bmonitorServer.start()

#获取服务器模板
def getServerTemplate():
    returnValue = {"suucess": True}
    returnValue["data"] = bmonitorServer.server.hostTemplate.templateGroup.keys()
    return returnValue

#添加服务模板
def addServerTemplate(serviceName):
    returnValue = {"suucess": True}
    baseTemplate = hosts.BaseTemplate()
    baseTemplate.name = serviceName
    bmonitorServer.server.hostTemplate.addTemplateGroup(baseTemplate)
    return returnValue

#获取所有的主机通过模版信息
def getAllHostByTemplate(templateName):
    return bmonitorServer.server.hostTemplate.templateGroup[templateName].hosts

#获取所有的服务通过模版信息
def getAllServiceByTemplate(templateName):
    return bmonitorServer.server.hostTemplate.templateGroup[templateName].services

#刷新主机配置信息到数据库。
def flushHostConfigToDb():
    return bmonitorServer.server.hostTemplate.flushToRedis()

'''
 获取所有的主机，这样用户可以通过选择的方式添加一个主机
 这里获取到的主机也是一个列表字典，用于展示各种主机数据。
'''
def getAllHost():
    hosts = []
    try:
        #从redis获取所有的主机列表,目前不考虑分页
        serverInfo = bmonitorServer.server.r.keys("HOSTINFO::*")
        for v in serverInfo:
            hosts.append(eval(bmonitorServer.server.r.get(v)))
        return hosts
    except:
        traceback.print_exc()
        return []

def clearHostToTemplate(templateName):
    bmonitorServer.server.hostTemplate.clearhosts(templateName)

def addHostToTemplate(ip,templateName):
        if templateName != "":
            if ip is None or ip == "":
                return
            bmonitorServer.server.hostTemplate.addHostToGroup(templateName,ip)

'''
  添加一个要管理的主机到redis中
  但这个主机没有关联任何监控服务组。
'''
def addAHost(hostip,templateName=""):
    returnValue = {"success": False}
    try:
        ip = hostip.get("ip",None)
        if ip is None or ip == "":
           returnValue["data"]= "ip is None"
           return returnValue

        key = "HOSTINFO::"+ip+"::"

        host = bmonitorServer.server.r.get(key)
        if host is None or host =='':
            bmonitorServer.server.r.set("HOSTINFO::"+ip+"::",hostip)
        else:
            hostInRedis = eval(host)
            hostInRedis.update(hostip)
            bmonitorServer.server.r.set("HOSTINFO::"+ip+"::",hostInRedis)


        returnValue["success"] = True
        return returnValue
    except:
        traceback.print_exc()
        return returnValue


def delAHost(hostip):
    returnValue = {"success": False}
    try:
        if hostip is None:
           returnValue["data"]= "ip is None"
           return returnValue
        bmonitorServer.server.r.delete("HOSTINFO::"+hostip+"::")
        returnValue["success"] = True
        return returnValue
    except:
        traceback.print_exc()
        return returnValue


def addAService(serviceName,templateName):
    bmonitorServer.server.hostTemplate.addServiceToGroup(templateName,serviceName)

'''
   添加主机的相关信息
'''
def addHostAddtionInfo(hostip,addtionInfo):
    pass


def getHostInfo(hostip):

    returnValue = {"success": True}
    hostKey = settings.REDIS_KEY_HOSTINFO % hostip
    #从redis中获取一个主机的基本数据，是一个map
    hostinfo = bmonitorServer.server.r.get(hostKey)
    if hostinfo is None:
        returnValue["success"]= False
        returnValue["data"] = "没有配置主机信息，请先添加主机！"
        return returnValue
    else:
        hostinredis = eval(hostinfo)
        if hostinredis.get("hostname",None) is None:
            returnValue["data"]=bmonitorServer.server.getClollectionHostInfo(hostip)
        else:
            returnValue["data"] = hostinredis
        return returnValue

'''
   根据主机ip获取一个主机的所有的基本监控信息
   数据初始化时已经进行过装载，所以，这里只需要每条数据返回一条即可
'''
def getHostMonitorInfo(host,type):

   #包含两组信息，一组是基本指标，一组是服务指标
   returnInfo = {"BASEINFO":{},
                 "SERVICEINFO":{}
                }

   #取得CPU的使用率

   if type == 'ALL':
          returnInfo["BASEINFO"] = DictUtil.LastUpdatedOrderedDict()
          returnInfo["BASEINFO"]["CPUUSAGE"] = bmonitorServer.server.getServiceReal(host,"linux_cpu","user")
          returnInfo["BASEINFO"]["MEMUSAGE"] = bmonitorServer.server.getServiceReal(host,"linux_mem","useage")
          returnInfo["BASEINFO"]["DISKUSAGE"] = 20
          returnInfo["BASEINFO"]["NETWORKUSAGE"] = 30
          #服务的状态
          returnInfo["SERVICEINFO"]["NORMAL"] = 50
          returnInfo["SERVICEINFO"]["WARN"] = 10
          returnInfo["SERVICEINFO"]["CRITICAL"] = 5

   return returnInfo


def filetranse(hostlist,filename,remote_path):
   returnInfo = []
   try:
       print(hostlist,remote_path,filename)
       for h in hostlist.split(","):
            hostKey = settings.REDIS_KEY_HOSTINFO % h
            hostinRedis = bmonitorServer.server.r.get(hostKey)
            if hostinRedis is None or hostinRedis == '':
                return {}
            else:
                hostinRedis = eval(hostinRedis)
            collectionValue = SSHUtil.sshputfile(h,hostinRedis.get("username",settings.SERVERUSER),
                                                 hostinRedis.get("password",settings.SERVERPASSWD),settings.UPLOAD_FOLDER,remote_path,filename)
            returnInfo.append(collectionValue)
   except:
       traceback.print_exc()

   return "\n".join(returnInfo)


def execcommand(hostlist,remote_command):
   returnInfo = []
   try:
       print(hostlist,remote_command)
       execcmd = []
       execcmd.append(remote_command)
       for h in hostlist.split(","):
            hostKey = settings.REDIS_KEY_HOSTINFO % h
            hostinRedis = bmonitorServer.server.r.get(hostKey)
            if hostinRedis is None or hostinRedis == '':
                return {}
            else:
                hostinRedis = eval(hostinRedis)
            print(hostinRedis)
            collectionValue = SSHUtil.ssh2(h,hostinRedis.get("username",settings.SERVERUSER),
                                           hostinRedis.get("password",settings.SERVERPASSWD),execcmd)
            returnInfo.append(str("在主机{0}上执行命令{1}，结果{2}".format(h,remote_command,collectionValue)))
   except:
       traceback.print_exc()


   print(returnInfo)
   return "<br>".join(returnInfo)